<template>
  <div style="width: 100%;height: 100%;">
    <div id="container">
      <div style="top: 20%;left:80%;border-radius: 5px;padding:30px 15px 15px 20px;box-sizing: border-box;border: 1px solid #3F96A5;box-shadow: inset 0px 0px 20px 0px rgba(63, 150, 165, 0.5);background: #021322;;height: 42vh;width: 10vw;position: relative;z-index:999">
        <div><h4>基本信息</h4></div>
        <div style="display:flex;margin-top: 20px">
          <img src="../../../public/images/wg.png" style="width: 20%">
          <div style="margin-left: 10%"><h4>网格数量</h4></div>
        </div>
        <div style="margin-left: 30%"><h3>{{form.grid}}</h3></div>
        <div style="display:flex;margin-top: 20px">
          <img src="../../../public/images/zyz.png" style="width: 20%">
          <div style="margin-left: 10%"><h4>志愿者数量</h4></div>
        </div>
        <div style="margin-left: 30%"><h3>{{form.volunteer}}</h3></div>
        <div style="display:flex;margin-top: 20px">
          <img src="../../../public/images/wg.png" style="width: 20%">
          <div style="margin-left: 10%"><h4>事件上报数量</h4></div>
        </div>
        <div style="margin-left: 30%"><h3>{{form.event}}</h3></div>
        <div style="display:flex;margin-top: 20px">
          <img src="../../../public/images/wg.png" style="width: 20%">
          <div style="margin-left: 10%"><h4>事件办结数量</h4></div>
        </div>
        <div style="margin-left: 30%"><h3>{{form.Completion}}</h3></div>

      </div>
    </div>
    <div class="infoTop">
      <img src="../../../public/images/start.png" style="width: 1.4vw;margin-right: 0.4vw">
      <span style="cursor:pointer;" v-for="(item,index) in recordsLog" :key="index" >
                <span @click="handleTap(index)">{{item.name}}</span>
                {{recordsLog.length - 1 === index ? '' : '-'}}</span>
    </div>
  </div>
</template>
<script>
// 安源区 矩形范围
const anyuanBounds = new AMap.Bounds(
  [113.769505, 27.542203],
  [113.996287, 27.721882]
)
// 图层数据集合
const ImageLayerMap = {
  安源区: {
    name: '安源区',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  白源街道: {
    name: '白源街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  横龙街道: {
    name: '横龙街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  安源镇: {
    name: '安源镇',
    url: require('../../../public/images/anyuanzhen.png'),
    bounds: anyuanBounds
  },
  青山镇: {
    name: '青山镇',
    url: require('../../../public/images/qinshanzhen.png'),
    bounds: anyuanBounds
  },
  高坑镇: {
    name: '高坑镇',
    url: require('../../../public/images/gaokenzhen.png'),
    bounds: anyuanBounds
  },
  丹江街道: {
    name: '丹江街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  八一街道: {
    name: '八一街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  光丰街道: {
    name: '光丰街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  五陂镇: {
    name: '五陂镇',
    url: require('../../../public/images/wupozhen.png'),
    bounds: anyuanBounds
  },
  凤凰街道: {
    name: '凤凰街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  东大街道: {
    name: '东大街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  },
  后埠街道: {
    name: '后埠街道',
    url: require('../../../public/images/anyuan5.png'),
    bounds: anyuanBounds
  }
}
export default {
  props: {
    reContry: Boolean // 父组件带有一个返回全国的操作按钮控制
  },
  data () {
    return {
      form: {
        grid: 360,
        Completion: 165,
        event: 168,
        volunteer: 2563
      },
      amap: null,
      activeStrokeColor: '#fff', // 当前展示区域描边颜色
      activeStrokeWeight: 4, // 当前展示区域线段粗细
      districtExplorer: null,
      tipMarker: null,
      $tipMarkerContent: null,
      currentAreaNode: null,
      aReContry: this.reContry,
      opts: {
        subdistrict: 3,
        extensions: 'all',
        level: 'district',
        showbiz: true
      },
      events: [],
      infoWindow: undefined, // 信息窗体
      recordsLog: [{ name: '萍乡市', level: 'city' }],
      ImageLayerObj: {

      }
    }
  },
  mounted () {
    const { name, level } = this.recordsLog[this.recordsLog.length - 1]
    this.initMap({ name, level, edit: false, zoom: 10 })
    // this.fetchFn()
  },
  computed: {
    // recordsLogComputed () {
    //   return this.recordsLog.map(n => n.name)
    // }
  },
  methods: {
    /**
     * @param name 已该位置为中心重新绘制地图标记
     * @param edit 是否是编辑模式 默认是初始化地图
     */
    initMap ({ name, edit, level, zoom }) {
      if (edit) {
        // 清理所有覆盖物 以及所有事件
        this.events.forEach(event => {
          AMap.event.removeListener(event)
        })
        this.events = []
        // 删除地图上所有的覆盖物 marker
        this.amap.clearMap()
        // 清除信息窗体
        this.infoWindow.close()
        // 清除图层
        // this.amapLayers.forEach(layer => {
        //   this.amap.remove(layer)
        // })
        // 隐藏图层
        this.hideLayer()
        // 记录操作
        this.recordsLogFn({ name, level })
        this.unlockMapBounds()
      }
      const that = this
      var district = new AMap.DistrictSearch(this.opts)
      district.search(name, function (status, result) {
        const { boundaries, center, districtList, level, adcode } = result.districtList[0]
        console.log(result, '-----DistrictSearch查询结果----')
        if (!edit) {
          that.amap = new AMap.Map('container', {
            defaultCursor: 'pointer',
            expandZoomRange: true,
            viewMode: '3D',
            center: [center.lng, center.lat], // 地图中心点
            zoom: zoom, // 地图显示的缩放级别
            resizeEnable: true, // 是否监控地图容器尺寸变化
            mapStyle: 'amap://styles/darkblue', // 地图样式
            features: ['road', 'building']
          })
        } else {
          // 设置中心点 与缩放等级
          that.amap.setZoom(zoom)
          that.amap.panTo(center)
        }
        that.lockMapBounds()
        // 绘制边界
        // 有贴图，不需要边界 目前只有安源区 以及一下不需要绘制
        if (adcode !== '360302') {
          that.mapPolyline(boundaries)
        } else {
          that.ImageLayerCreate(name)
        }
        // 绘制区划 或 街道中心点
        if (level === 'district') {
          for (let i = 0; i < districtList.length; i++) {
            that.mapMarker(districtList[i])
          }
        } else {
          for (let i = 0; i < districtList.length; i++) {
            that.mapPolygon(districtList[i])
          }
        }
      })
    },
    // 绘制区域
    mapPolygon ({ name, level }) {
      const that = this
      const district = new AMap.DistrictSearch(this.opts)
      district.search(name, function (status, result) {
        const { boundaries, center } = result.districtList[0]
        const polygon = new AMap.Polygon({
          path: boundaries[0].map(n => [n.lng, n.lat]),
          strokeColor: '#fff',
          strokeWeight: 3,
          strokeOpacity: 0.4,
          fillOpacity: 0.4,
          fillColor: '#1791fc',
          zIndex: 50,
          bubble: true
        })
        polygon.setMap(that.amap)
        const polygonMouseover = AMap.event.addListener(polygon, 'mouseover', (e) => {
          polygon.setOptions({
            fillOpacity: 0.4,
            fillColor: '#fff'
          })
          that.openInfo(name, center)
        })
        const polygonMouseout = AMap.event.addListener(polygon, 'mouseout', (e) => {
          polygon.setOptions({
            fillOpacity: 0.4,
            fillColor: '#1791fc'
          })
          that.infoWindow.close()
        })
        const polygonClick = AMap.event.addListener(polygon, 'click', (e) => {
          that.initMap({ name, edit: true, level, zoom: 12 })
        })
        // 收集事件
        that.events.push(polygonMouseover)
        that.events.push(polygonMouseout)
        that.events.push(polygonClick)
      })
    },
    // 创建纯文本标记
    // createText(){
    //   var text = new AMap.Text({
    //       text:'纯文本标记',
    //       anchor:'center', // 设置文本标记锚点
    //       draggable:true,
    //       cursor:'pointer',
    //       angle:10,
    //       style:{
    //           'padding': '.75rem 1.25rem',
    //           'margin-bottom': '1rem',
    //           'border-radius': '.25rem',
    //           'background-color': 'white',
    //           'width': '15rem',
    //           'border-width': 0,
    //           'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
    //           'text-align': 'center',
    //           'font-size': '20px',
    //           'color': 'blue'
    //       },
    //       position: [116.396923,39.918203]
    //   });
    // },
    // 鼠标悬浮打开信息窗体
    openInfo (name, center) {
      let grid = 360
      let peopon = 1452
      if (name === '八一街道') {
        grid = 22
        peopon = 45
      } else if (name === '基建村一网格') {
        grid = 1
        peopon = 34
      } else if (name === '基建村二网格') {
        grid = 1
        peopon = 2
      } else if (name === '天佑街后段网格') {
        grid = 1
        peopon = 6
      } else if (name === '联西网格') {
        grid = 1
        peopon = 3
      }
      // 构建信息窗体中显示的内容
      var info = []
      info.push(`<div style="border-radius: 5px;width: 345px;height: 163px;padding:30px 15px 15px 20px;box-sizing: border-box;border: 1px solid #3F96A5;box-shadow: inset 0px 0px 20px 0px rgba(63, 150, 165, 0.5);background: #021322;">
<h4>${name}</h4>
<div style="color: #C0D2E2;margin-top: 30px"><h4>网格数：${grid}个</h4></div>
<div style="color: #C0D2E2;margin-top: 15px"><h4>志愿者人数：${peopon}人</h4></div>
</div>`)
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true,
        offset: new AMap.Pixel(10, -20),
        content: info.join('') // 使用默认信息窗体框样式，显示信息内容
      })
      this.infoWindow.open(this.amap, new AMap.LngLat(center.lng, center.lat))
    },

    mapMarker ({ name, center, adcode, level }) {
      const that = this
      const marker = this.markerCreate({ name, center })
      const markerClick = AMap.event.addListener(marker, 'click', (e) => {
        // 设置中心点 与缩放等级 如果当前已经记录了改地址则不再记录
        this.recordsLogFn({ name, level, center })
        // 根据选择的镇，切换贴图
        that.switchLayer({ adcode, center, name })
        that.amap.setZoomAndCenter(14, center)
      })
      that.events.push(markerClick)
      // 安源
      // if (adcode === '360302') {
      //   that.ImageLayerCreate(name)
      // }
    },
    ImageLayerCreate (name) {
      if (this.ImageLayerObj[name]) {
        this.ImageLayerObj[name].show()
      } else {
        const { url, bounds } = ImageLayerMap[name]
        if (url && bounds) {
          const imageLayer = new AMap.ImageLayer({
            url,
            bounds,
            zooms: [9, 20]
          })
          // 设置图层
          imageLayer.setMap(this.amap)
          // this.amap.setLayers([
          //   new AMap.TileLayer(),
          //   imageLayer
          // ])
          this.ImageLayerObj[name] = imageLayer
        }
      }
    },
    // 创建标记点
    markerCreate ({ center, name }) {
      const that = this
      const marker = new AMap.Marker({ // 图标尺寸
        icon: '', // 点标记图片路径
        position: [center.lng, center.lat], // 位置
        topWhenClick: true,
        zIndex: 999
      })
      marker.setLabel({
        direction: 'bottom',
        offset: new AMap.Pixel(15, 20), // 设置文本标注偏移量
        content: `<div class="marker_label1" style="color: blue">${name}</div>` // 设置文本标注内容
      })
      marker.setMap(this.amap)
      const markerMouseover = AMap.event.addListener(marker, 'mouseover', (e) => {
        // 打开信息窗体
        that.openInfo(name, center)
      })
      const markerMouseout = AMap.event.addListener(marker, 'mouseout', (e) => {
        // 关闭信息窗体
        that.infoWindow.close()
      })
      this.events.push(markerMouseover)
      this.events.push(markerMouseout)
      return marker
    },

    // 描边
    mapPolyline (bounds) {
      // 添加描边
      for (let i = 0; i < bounds.length; i++) {
        const polyline = new AMap.Polyline({
          path: bounds[i], // polyline 路径，支持 lineString 和 MultiLineString
          strokeColor: this.activeStrokeColor,
          strokeWeight: this.activeStrokeWeight
        })
        polyline.setMap(this.amap)
      }
    },
    // 获取街道信息
    fetchFn () {
      fetch('https://restapi.amap.com/rest/me/polygon/dataquery/street?key=ddfca4544dd6b993c3f7a276c53f8efd&showPolygon=1&adcode=110114&pageSize=2&pageNum=1').then(res => {
        console.log(res, '===')
      })
    },
    // 记录操作
    recordsLogFn ({ name, level, center }) {
      if (name === '八一街道') {
        this.form.grid = 22
        this.form.volunteer = 45
      }else {
        this.form.grid = 360
        this.form.volunteer = 2354
      }
      const lastData = this.recordsLog[this.recordsLog.length - 1]
      if (lastData.name === name && lastData.level === level) {
        // 名称相等，层级相等 则不用处理
        return false
      } else if (lastData.name !== name && lastData.level === level) {
        // 名称不相等，层级相等 则替换
        this.$set(this.recordsLog, this.recordsLog.length - 1, {
          name,
          level,
          center
        })
        return true
      } else if (lastData.level !== level) {
        // 层级不相等直接push
        this.recordsLog.push({
          name,
          level,
          center
        })
        return true
      }
    },
    // 隐藏所有图层
    hideLayer () {
      Object.keys(this.ImageLayerObj).map(n => {
        this.ImageLayerObj[n].hide()
      })
    },
    // 切换图层
    switchLayer ({ adcode, center, name }) {
      // 清除图层
      // this.amapLayers.forEach(layer => {
      //   this.amap.remove(layer)
      // })
      this.hideLayer()
      // 清除所有覆盖物
      this.amap.clearMap()
      // 重新绘点击的节点
      this.markerCreate({ center, name })
      // 绘制改节点对应的贴图
      this.ImageLayerCreate(name)
      // 绘制 网格 节点
      if (name === '八一街道') {
        const gridDom = [{
          center: {
            lat: 27.627267,
            lng: 113.844734
          },
          name: '联西网格'
        },
        {
          center: {
            lat: 27.6283,
            lng: 113.846025
          },
          name: '天佑街后段网格'
        },
        {
          center: {
            lat: 27.628958,
            lng: 113.844829
          },
          name: '基建村一网格'
        },
        {
          center: {
            lat: 27.629596,
            lng: 113.845852
          },
          name: '基建村二网格'
        }
        ]
        gridDom.forEach(item => {
          this.markerCreate({ center: item.center, name: item.name })
        })
      }
    },
    // 切换定位
    handleTap (index) {
      const { level, center, name } = this.recordsLog[index]
      if (index === 2) {
        // 目前层级 最多3层 最后一层则直接重新定位
        this.amap.setZoomAndCenter(14, center)
      } else if (index === 1) {
        this.recordsLog = [
          { name: '萍乡市', level: 'city' },
          { name, level }
        ]
        this.initMap({ name, edit: true, level, zoom: 12 })
      } else if (index === 0) {
        this.recordsLog = [
          { name: '萍乡市', level: 'city' }
        ]
        this.initMap({ name, edit: true, level, zoom: 10 })
      }
    },
    // 地图显示限制
    lockMapBounds () {
      var bounds = this.amap.getBounds()
      this.amap.setLimitBounds(bounds)
    },
    // 取消地图显示限制
    unlockMapBounds () {
      this.amap.clearLimitBounds()
    }
  }
}
</script>
<style lang="less">
.infoTop{
  background-color: #021322;
  color: #fff;
  height: 30px;
  line-height: 30px;
  font-size: 18px;
  margin-bottom: 1rem;
  border-radius: .25rem;
  position: fixed;
  top: 3rem;
  border-width: 0;
  //box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
}

</style>
